package com.x.control;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.x.model.User;
import com.x.service.transactional.PaddingService;
import com.x.service.transactional.UserService;

@Controller
@RequestMapping("/padding")
public class PaddingController {

	@Autowired(required = true)
	PaddingService paddingService;
	@Autowired(required = true)
	UserService userService;

	String[] columns = { "id", "fc", "shipMethod", "province", "city",
			"district", "padding", "startDate", "endDate" };

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request) {
		int startIndex = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String draw = request.getParameter("draw");
		List<String[]> odrerPart = new ArrayList<>();
		List<String[]> wherePart = new ArrayList<>();
		for (int i = 0; i < columns.length; i++) {
			String orderColumn = request.getParameter("order[" + i
					+ "][column]");
			if (orderColumn != null) {
				String orderDir = request.getParameter("order[" + i + "][dir]");
				odrerPart.add(new String[] {
						columns[Integer.parseInt(orderColumn)], orderDir });
			}
			String searchable = request.getParameter("columns[" + i
					+ "][searchable]");
			if (searchable.equals("true")) {
				String searchColumn = columns[i];
				String value = request.getParameter("columns[" + i
						+ "][search][value]");
				if (!value.isEmpty()) {
					wherePart.add(new String[] { searchColumn, value });
				}
			}

		}

		Map<String, Object> result = paddingService.list(startIndex, length,
				wherePart, odrerPart);
		result.put("draw", draw);
		return result;
	}

	@RequestMapping(value = "/find/{id}")
	@ResponseBody
	public Map<String, Object> find(@PathVariable(value = "id") String id) {
		return paddingService.find(id);
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	String delete(@RequestParam("id") String id) {
		paddingService.delete(id);
		return "redirect:/home/newPadding";
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	ModelAndView create(@RequestParam("fc") String fc,
			@RequestParam("sm") String sm,
			@RequestParam("padding") String padding,
			@RequestParam("province") String province,
			@RequestParam("city") String city,
			@RequestParam("district") String district,
			@RequestParam("startDate") String statDate,
			@RequestParam("endDate") String endDate) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("nav", "newPadding");
		mv.setViewName("home");
		try {
			String fcName = fc.toUpperCase();
			String smName = sm.toUpperCase();
			int paddingHour = Integer.parseInt(padding);
			String provinceName = province.toUpperCase();
			String cityName = city.toUpperCase();
			String districtName = district.toUpperCase();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date start = format.parse(statDate);
			Date end = format.parse(endDate);
			if (paddingService.noConflict(fcName, smName, provinceName,
					cityName, districtName, start, end)) {
				paddingService.create(fcName, smName, paddingHour,
						provinceName, cityName, districtName, start, end);
			} else {
				mv.addObject("error", "create padding fail: Duplicate Users!");
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mv;

	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	String update(@RequestParam("id") String id, @RequestParam("fc") String fc,
			@RequestParam("sm") String sm,
			@RequestParam("province") String province,
			@RequestParam("city") String city,
			@RequestParam("district") String district,
			@RequestParam("startDate") String startDate,
			@RequestParam("endDate") String endDate) {
		paddingService.update(id, fc, sm, province, city, district, startDate,
				endDate);
		return "redirect:/home/newPadding";
	}

	@RequestMapping(value = "/suggest/fc/{fc}")
	@ResponseBody
	public List<String> suggestFC(@PathVariable(value = "fc") String fc)
			throws UnsupportedEncodingException {
		List<String> result = paddingService.getFCSuggestion(fc);
		return result;

	}

	@RequestMapping(value = "/suggest/sm/{sm}")
	@ResponseBody
	public List<String> suggestSM(@PathVariable(value = "sm") String sm)
			throws UnsupportedEncodingException {
		List<String> result = paddingService.getSMSuggestion(sm);
		return result;

	}

	@RequestMapping(value = "/suggest/province/{province}")
	@ResponseBody
	public List<String> suggestProvince(
			@PathVariable(value = "province") String province)
			throws UnsupportedEncodingException {
		List<String> result = paddingService.getProvinceSuggestion(province);
		return result;

	}

	@RequestMapping(value = "/suggest/city/{city}")
	@ResponseBody
	public List<String> suggestCity(@PathVariable(value = "city") String city)
			throws UnsupportedEncodingException {
		List<String> result = paddingService.getCitySuggestion(city);
		return result;

	}

	@RequestMapping(value = "/suggest/district/{district}")
	@ResponseBody
	public List<String> suggestDistrict(
			@PathVariable(value = "district") String district)
			throws UnsupportedEncodingException {
		List<String> result = paddingService.getDistrictSuggestion(district);
		return result;

	}

	@RequestMapping(value = "/suggest/padding/{padding}")
	@ResponseBody
	public List<String> suggestPadding(
			@PathVariable(value = "padding") String padding)
			throws UnsupportedEncodingException {
		List<String> result = paddingService.getPaddingSuggestion(padding);
		return result;

	}

	@RequestMapping(value = "/submit")
	public String submitPadding(@RequestParam("tt") String tt,
			@RequestParam("reason") String reason) {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String username;
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		User user = userService.getUserByName(username);
		paddingService.submit(tt, reason, user.getId());
		return "redirect:/home/newPadding";

	}
}
